package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LeYouException;
import com.leyou.cart.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * create by Rose on 2020/1/11
 */
@Slf4j
@Service
@EnableConfigurationProperties({UploadProperties.class})
public class UploadService {

    @Autowired
    private UploadProperties uploadProperties;

    private static  final Logger logger = LoggerFactory.getLogger(UploadService.class);
    /**
     *     支持的文件类型
     */
    private static  final List<String> allowTypes = Arrays.asList("image/png","image/jpeg");

    @Autowired
    private FastFileStorageClient storageClient ;

    public String upload(MultipartFile file){
        try {
            // 1 文件的校验, 图片信息校验
            // 1.1 校验文件类型
            String contentType = file.getContentType();
            if(!uploadProperties.getAllowTypes().contains(contentType)){
                logger.info("上传失败，文件类型不匹配：{}",contentType);
                throw new LeYouException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            // 1.2 校验数据内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image == null ){
                logger.info("上传失败，文件内容不符合要求");
                throw new LeYouException(ExceptionEnum.INVALID_FILE_TYPE);
            }

            // 2 保存图片
            // 2.1 生成保存目录
            File dir  = new File("D:\\heima\\upload");
            // 保存到某个位置
            //file.transferTo(new File(dir,file.getOriginalFilename()));

            // 上传到FastDFS
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), getExtension(file.getOriginalFilename()), null);

            // 3 生成图片地址
            //String url = "http://image.leyou.com/upload/" + file.getOriginalFilename();

            String url = uploadProperties.getBaseUrl() + storePath.getFullPath();
            log.info("上传地址为：url = {}",url);
            return url ;
            
        }catch (Exception e){
            e.printStackTrace();
            logger.error("文件上传失败：文件名: {} ", file.getOriginalFilename(), e);
            throw new LeYouException(ExceptionEnum.UPLOAD_FILE_ERROR);
            // return  null;
        }
    }

    public String getExtension(String fileName){
       return StringUtils.substringAfterLast(fileName,".");
    }

}
